package com.vinfai.thread.tradition;
/**
 *
 * 四个线程a,b,c,d. 线程a,b对变量i加一. 线程c,d对变量i减去一.四个线程顺序执行, 每个线程每次只执行一次.i的初始值为0， 打印结果0 1 2 1 0 1 2 1 0 1 2...
 * 这道题还是有一定的难度的. 因为要求顺序执行. 不能简单用同步.
 * @author vinfai
 */
public class ThreadExample {

	public static void main(String[] args) {
		final ShareData data = new ShareData();
		//启动四个线程
		new Thread(new Runnable(){
			public void run() {
				data.increase(0);
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				data.increase(1);
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				data.decrease(2);
			}
		}).start();
		new Thread(new Runnable(){
			public void run() {
				data.decrease(3);
			}
		}).start();
	}
}
//公共代码块
class ShareData{
	private int i = 0;
	private int j = 0;
	//增加数据
	public synchronized void increase(int threadIndex){
		while(j!=threadIndex){
			try {
				System.out.println("thread "+threadIndex+" is wait......");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("thread "+j+" value is :"+i);
		i++;
		j = (j+1)%4;
		this.notifyAll();
	}
	//减少数据
	public synchronized void decrease(int threadIndex){
		while(j!=threadIndex){
			try {
				System.out.println("thread "+threadIndex+" is wait.2.....");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("thread "+j+" value is :"+i);
		i--;
		j = (j+1)%4;
		this.notifyAll();
	}
}
